<script setup lang="ts">
import { debounce, formatTime, generateSerialNumber, generateUUID,  } from '@/renderer/utils/helper';
import { message } from 'ant-design-vue';
import { NoteType } from '@/renderer/utils/helper';
import { computed, inject, nextTick, ref, toRefs } from 'vue';
import MoveFolder from './MoveFolder.vue';

const setNoteTitleEditing = inject<any>('setNoteTitleEditing')

const emits = defineEmits(['handelSubmit', 'handleExpandSider', 'update:isEditing', 'update:currentNote', 'update:currentFolder'])
const props = defineProps<{
    notes: any[]
    currentFolder: any,
    currentNote: any
    isEditing: boolean,
    isSiderCoverShow: boolean,
    siderCoverOpacity: number,
    siderBlur: number,
    siderCoverFilter: string,
    getNoteList: () => Promise<any>
}>()
const { notes, currentFolder, currentNote, getNoteList } = toRefs(props)

const handelSubmit = async (note: any, type: string) => {
    emits('handelSubmit', note, type)
}
const getNoteById = (id: string) => {
    return notes.value.find((note: { id: any; }) => note.id === id)
}

const inputRefs = ref<any[]>([]);
const setItemInputRef = (el: any, item: any) => {
    if (el) {
        inputRefs.value[item.id] = el;
    }
};

const focusInput = (item: any) => {
    item.titleIsEditing = true
    setTimeout(() => {
        inputRefs.value[item.id].focus();
    }, 0);
};

const addNote = debounce(async (type = NoteType.Document) => {
    const isFolder = type === NoteType.Folder
    let serialNumber = generateSerialNumber();
    const note = {
        id: generateUUID(),
        parentId: currentFolder.value.id ?? null,
        type: type ?? NoteType.Document,
        isFolder: isFolder,
        title: `新建${isFolder ? '文件夹' : '文档'}` + serialNumber,
        content: isFolder ? '' : "请编辑文档......",
        created: formatTime(Date.now()),
        updated: formatTime(Date.now()),
    };
    try {
        // 通过API创建新笔记
        const response = await fetch('http://localhost:32068/api/memorys', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(note),
        });
        
        const result = await response.json();
        if (result.code === 201) {
            let noteList = (await getNoteList.value()) ?? [];
            let getNowNote = noteList.find((item: any) => item.id === note.id)
            emits('update:currentNote', getNowNote ?? {})
            message.success("添加成功");
        } else {
            message.error("添加失败");
        }
    } catch (error) {
        message.error("添加失败");
        console.error("添加笔记失败:", error);
    }

    setTimeout(() => {
        setNoteTitleEditing()
        nextTick(() => {
            // 这里可能需要检查inputRefs是否还有效
            if (inputRefs.value[currentNote.value.id]) {
                inputRefs.value[currentNote.value.id].focus();
            }
        })
    }, 100);
}, 200)

const deepRemove = async (note: any) => {
    if (note.isFolder) {
        const children = notes.value.filter((item: any) => item.parentId === note.id);
        for (const child of children) {
            await deepRemove(child);
        }
    }
    try {
        // 通过API删除笔记
        const response = await fetch(`http://localhost:32068/api/memorys/${note.id}`, {
            method: 'DELETE',
        });
        
        const result = await response.json();
        if (result.code !== 200) {
            throw new Error('删除失败');
        }
    } catch (error) {
        console.log(error);
        throw error;
    }
};

const removeNote = async (note: any) => {
    if (currentNote.value?.id + "" == note.id + "") {
        emits("update:currentNote", {});
    }
    try {
        await deepRemove(note);
        message.success("删除成功");
        await getNoteList.value();
    } catch (error) {
        message.error("删除失败");
    }
};

const openNote = async (note: any) => {
    emits('update:isEditing', false)
    emits('update:currentNote', note)
};

const entryFolder = async (note: any) => {
    emits('update:currentFolder', note)
};

const returnPreviousLevel = () => {
    if (currentFolder.value.parentId) {
        const parent = getNoteById(currentFolder.value.parentId)
        emits('update:currentFolder', parent)
    } else {
        emits('update:currentFolder', {})
    }
}

const handleExpandSider = () => {
    emits('handleExpandSider')
};

// const getList = () => {
//     emits('getNoteList')
// }

const initSetDefaultNote = () => {
    let currentNote =
        filterMemoList.value && filterMemoList.value.length > 0 ? filterMemoList.value.filter((item: any) => !item.isFolder)[0] ?? {} : {};
    emits('update:currentNote', currentNote)
}
defineExpose({
    initSetDefaultNote
})


const filterString = ref<string>('')
const filterMemoList = computed(() => {
    if (filterString.value) {
        const filterValue = filterString.value.toLowerCase().trim();
        return notes.value.filter((item: { title: string; isFolder: boolean }) =>
            item.title.toLowerCase().trim().includes(filterValue) && !item.isFolder
        )
    } else {

        if (currentFolder.value.id) {
            return notes.value.filter((item: { parentId: string; isFolder: boolean }) =>
                item.parentId === currentFolder.value.id
            )
        } else {
            return notes.value.filter((item: { parentId: string; isFolder: boolean }) => {
                return !item.parentId
            })
        }

    }
})


const moveFolderRef = ref<any>(null)
const handelMoveFolder = (item: any) => {
  moveFolderRef.value.openModal(item);
};

// 添加/取消收藏功能
const toggleStar = async (note: any) => {
  const updatedNote = { ...note, isStar: !note.isStar, updated: formatTime(Date.now()) };
  
  try {
    // 通过API更新笔记
    const response = await fetch(`http://localhost:32068/api/memorys/${note.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(updatedNote),
    });
    
    const result = await response.json();
    if (result.code === 200) {
      // 更新本地列表
      const index = props.notes.findIndex((n: any) => n.id === note.id);
      if (index !== -1) {
        props.notes[index] = updatedNote;
      }
      
      // 如果是当前笔记，也要更新
      if (props.currentNote.id === note.id) {
        emits('update:currentNote', updatedNote);
      }
      
      message.success(updatedNote.isStar ? '已添加到收藏' : '已取消收藏');
    } else {
      throw new Error('更新失败');
    }
  } catch (error) {
    message.error('操作失败');
    console.error(error);
  }
};

const handleMoveFolderOk = async (id: any) => {
    console.log('id', id)
    const pureNote = { ...currentNote.value, updated: formatTime(Date.now()) }; // 浅拷贝
    pureNote.parentId = id ? id: null;  // 确保正确设置parentId，即使是null值
    console.log('pureNote', pureNote)
    
    try {
        // 通过API更新笔记
        const response = await fetch(`http://localhost:32068/api/memorys/${currentNote.value.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(pureNote),
        });
        
        const result = await response.json();
        if (result.code === 200) {
            await getNoteList.value();
            message.success("移动成功");
        } else {
            message.error("移动失败");
        }
    } catch (error) {
        message.error("移动失败");
        console.error("移动笔记失败:", error);
    }
}

</script>

<template>

    <div class="bar-body">
        <div class="bar-header">
            <a-input v-model:value.trim="filterString" allowClear placeholder="请输入..."></a-input>
            <a-dropdown :trigger="['click']" placement="right" :arrow="{ pointAtCenter: true }">
                <span @click.stop.prevent="" class="iconfont icon-add" style="cursor: pointer;margin-left: 8px;"></span>
                <template #overlay>
                    <a-menu style="width: 120px;">
                        <a-menu-item @click.stop="addNote(NoteType.Document)">
                            <div style="cursor: pointer;color: #266fe8;font-size: 13px">文档</div>
                        </a-menu-item>
                        <a-menu-item @click.stop="addNote(NoteType.Folder)">
                            <div style="cursor: pointer;color: #266fe8;font-size: 13px">文件夹</div>
                        </a-menu-item>
                    </a-menu>
                </template>
            </a-dropdown>
        </div>
        <div class="folder-header" v-if="currentFolder.id">
            <span :class="['iconfont icon-fanhuishangyiji',]" @click="returnPreviousLevel"
                style="cursor: pointer;width: 40px;"></span>
            <span class="folder-title" :title="currentFolder.title">{{ currentFolder.title }}</span>
        </div>
        <div class="note-list" :style="{ height: currentFolder.id ? 'calc(100% - 90px)' : 'calc(100% - 45px)' }">
            <div v-if="filterMemoList.length > 0" class="note-item" v-for="(item, index) in filterMemoList" :key="index"
                @click="openNote(item)">
                <span :class="['iconfont', item.isFolder ? 'icon-wenjianjia' : 'icon-wenjian']"
                    style="cursor: pointer"></span>

                <div v-if="!item.titleIsEditing" :class="['note-title', { isSelectNote: currentNote.id == item.id }]">
                    <span v-if="item.isFolder" class="folder-name" @click.stop="entryFolder(item)">{{ item.title
                        }}</span>
                    <span v-else class="document-name">{{ item.title }}</span>
                </div>
                <div v-else class="note-title-input">
                    <a-input :ref="(el: any) => setItemInputRef(el, item)" v-model:value="item.title"
                        @blur="handelSubmit(item, 'title')" @pressEnter="item.titleIsEditing = !item.titleIsEditing"></a-input>
                </div>
                <div>

                    <div @click.stop.prevent="" v-if="item.id == currentNote.id">
                        <a-dropdown :trigger="['click']" placement="right" :arrow="{ pointAtCenter: true }">
                            <span class="iconfont icon-gengduo" @click.stop.prevent="" style="
                                cursor: pointer;
                                color: #266fe8;
                                font-size: 13px;
                                margin-right: 5px;
                            "></span>
                            <template #overlay>
                                <a-menu style="width: 120px;">
                                    <a-menu-item @click.stop="focusInput(item)">
                                        <div style="cursor: pointer;color: #266fe8;font-size: 13px">重命名</div>
                                    </a-menu-item>
                                    <a-menu-item  @click.stop="handelMoveFolder(item)">
                                        <div style="cursor: pointer;color: #266fe8;font-size: 13px">移动到</div>
                                    </a-menu-item>
                                    <a-menu-item  v-if="!item.isFolder" @click.stop="toggleStar(item)">
                                        <div style="cursor: pointer;color: #266fe8;font-size: 13px">
                                            {{ item.isStar ? '取消收藏' : '收藏' }}
                                        </div>
                                    </a-menu-item>
                                    <a-popconfirm title="确定要删除该记录?" ok-text="是" cancel-text="否"
                                        @confirm="removeNote(item)">
                                        <a-menu-item>
                                            <div style="cursor: pointer; color: red; font-size: 13px">删除</div>
                                        </a-menu-item>
                                    </a-popconfirm>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>

                </div>
            </div>
            <div v-else style="font-size: 13px; padding: 40px;color:#898989;text-align: center; opacity: 0.7;">
                <div>
                    <span class="iconfont icon-kongshuju" style="font-size: 48px; margin-bottom: 16px; display: block;"></span>
                    <div>暂无记录~</div>
                </div>
            </div>
        </div>

    </div>
    <div @click="handleExpandSider" v-show="isSiderCoverShow" class="sider-cover" :style="{
        backgroundColor: `rgba(255, 255, 255, ${siderCoverOpacity})`,
        backdropFilter: `blur(${siderBlur}px)`,
        filter: siderCoverFilter,
    }">
        <span
            style="writing-mode:vertical-lr;letter-spacing:5px;font-size: 15px;color: #266fe8;cursor: pointer;">展开所有笔记</span>
    </div>

    <MoveFolder ref="moveFolderRef" @handleOk="handleMoveFolderOk"></MoveFolder>

</template>

<style scoped>
.sider-bar {
    /* min-width: 200px; */
    flex: 1 0 0px;
    height: 100%;
    /* 继承父容器高度 */
    display: flex;
    flex-direction: column;
    /* border-right: 1px solid rgba(0, 0, 0, 0.1); */
    padding: 15px 0;
    overflow: hidden;
    position: relative;
}

.bar-body {
    height: 100%;
    overflow-y: auto;
}

.sider-bar .sider-cover {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 998;
    background-color: transparent;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.7);
    user-select: none;
    cursor: pointer;
    overflow: hidden;
}

/* 禁止整个组件内的文本被选中 */
.no-select {
    -webkit-user-select: none;
    /* Safari */
    -ms-user-select: none;
    /* IE 10+ */
    user-select: none;
    /* Standard */
    cursor: pointer;
}

.bar-header {
    flex: 0 0 auto;
    height: 45px;
    line-height: 30px;
    font-size: 14px;
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
}

.folder-header {
    height: 45px;
    display: flex;
    font-size: 14px;
    padding: 0 10px;
    align-items: center;
    border-bottom: 1px solid #e8e8e8;
    /* 添加卡片阴影效果 */
    overflow: hidden;
    font-weight: 500;
    flex: 1 1 auto;
}

.folder-title {
    flex: 1 1 auto;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding-right: 20px;
    color: #232d47;
}

.note-list {
    flex: 1 1 auto;
    overflow-y: auto;
    /* 内容过多时显示滚动条 */
    overflow-x: hidden;
    padding: 10px;
    height: calc(100% - 45px);
}

.note-item {
    height: 50px;
    line-height: 50px;
    font-size: 13px;
    padding-left: 5px;
    padding-right: 5px;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px dashed rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.isSelectNote {
    color: #266fe8;
}

.note-title {
    padding-right: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: left;
    margin-right: auto;
    margin-left: 10px;
}

.folder-name:hover {
    text-decoration: underline;
}


.note-title-input {
    padding-right: 10px;
    margin-right: auto;
    margin-left: 10px;
    flex: 1;
}


.resize-bar {
    flex: 0 0 4px;
    position: relative;
    color: rgba(0, 0, 0, 0.1);
    border-left: 1px solid rgba(0, 0, 0, 0.1);
}

.resize-bar:hover,
.entry-resizing {
    cursor: col-resize;
}

.resize-bar::before {
    content: "";
    position: absolute;
    top: calc(50% - 21px);
    left: 50%;
    transform: translateX(-50%);
    width: 2px;
    height: 2px;
    border-radius: 50%;
    user-select: none;
    display: flex;
    flex-direction: column;
    background-color: currentColor;
    box-shadow: 0 8px 0 currentColor, 0 16px 0 currentColor, 0 24px 0 currentColor,
        0 32px 0 currentColor, 0 40px 0 currentColor;
}

.resize-bar::after {
    content: "";
    position: absolute;
    width: 2px;
    height: 100%;
    border-radius: 10px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: transparent;
    transition: background-color 0.3s ease;
}

.resize-bar:hover::after,
.entry-resizing::after {
    background-color: #266fe8;
}


/* 默认隐藏 */
/* .icon-gengduo {
  display: none;

} */
/* 鼠标悬停时显示 */
/* .note-item:hover .icon-gengduo {
  display: inline-block;

} */

.icon-wenjianjia {
    color: #ffbf00;
}

/* 美化笔记项样式 */
.note-item {
    padding: 8px 10px;
    margin: 0 5px 8px;
    border-radius: var(--border-radius);
    transition: var(--transition);
    cursor: pointer;
    display: flex;
    align-items: center;
    background-color: var(--surface-color);
    border: 1px solid var(--border-color);
}

.note-item:hover {
    background-color: var(--primary-extra-light-color);
    border-color: var(--primary-color);
}

.note-item.active {
    background-color: var(--primary-color);
    border-color: var(--primary-hover-color);
    color: white;
}

.note-item.active .time {
    color: rgba(255, 255, 255, 0.8);
}

.note-item .title {
    flex: 1;
    margin: 0 8px;
    font-size: 14px;
}

.note-item .time {
    font-size: 12px;
    color: var(--text-placeholder);
}

.note-item .actions {
    display: none;
    margin-left: 8px;
}

.note-item:hover .actions {
    display: flex;
    gap: 4px;
}

.note-item .actions button {
    border: none;
    background: transparent;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    color: var(--text-secondary);
    transition: var(--transition);
}

.note-item .actions button:hover {
    background-color: var(--border-color);
    color: var(--primary-color);
}

/* 美化文件夹树样式 */
.folder-tree {
    padding: 8px 0;
    margin: 0 12px 16px; /* 增加底部边距 */
    background-color: var(--surface-color);
    border-radius: var(--border-radius);
    border: 1px solid var(--border-color);
}

.folder-tree .ant-tree-treenode {
    padding: 2px 0;
}

.folder-tree .ant-tree-node-content-wrapper {
    border-radius: var(--border-radius);
    transition: var(--transition);
    margin: 0 4px;
}

.folder-tree .ant-tree-node-content-wrapper:hover {
    background-color: var(--primary-extra-light-color);
}

.folder-tree .ant-tree-node-selected {
    background-color: var(--primary-color) !important;
    color: white;
}

/* 美化搜索框 */
.search-input {
    margin: 0 12px 16px; /* 增加底部边距 */
    border-radius: var(--border-radius);
    border: 1px solid var(--border-color);
}

.search-input .ant-input {
    border: none !important;
    border-radius: var(--border-radius) !important;
}

.search-input .ant-input:focus {
    box-shadow: none !important;
}

/* 美化按钮 */
.add-note-btn {
    margin: 0 12px 16px; /* 增加底部边距 */
    background-color: var(--surface-color);
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
    transition: var(--transition);
}

.add-note-btn:hover {
    background-color: var(--primary-extra-light-color);
    border-color: var(--primary-color);
    color: var(--primary-hover-color);
}

/* 美化折叠面板 */
.ant-collapse {
    margin: 0 12px 12px;
    border: 1px solid var(--border-color) !important;
    border-radius: var(--border-radius) !important;
    background-color: var(--surface-color);
    overflow: hidden;
}

.ant-collapse > .ant-collapse-item {
    border-bottom: 1px solid var(--border-color);
}

.ant-collapse > .ant-collapse-item:last-child {
    border-bottom: none;
}

.ant-collapse > .ant-collapse-item > .ant-collapse-header {
    background-color: var(--surface-color);
    transition: var(--transition);
}

.ant-collapse > .ant-collapse-item > .ant-collapse-header:hover {
    background-color: var(--primary-extra-light-color);
}

.ant-collapse-content {
    background-color: var(--surface-color);
    border-top: 1px solid var(--border-color);
}

/* 美化折叠面板中的笔记项 */
.folder-note-item {
    padding: 8px 16px;
    margin: 4px;
    border-radius: var(--border-radius);
    transition: var(--transition);
    cursor: pointer;
    display: flex;
    align-items: center;
    background-color: var(--surface-color);
    border: 1px solid var(--border-color);
}

.folder-note-item:hover {
    background-color: var(--primary-extra-light-color);
    border-color: var(--primary-color);
}

.folder-note-item.active {
    background-color: var(--primary-color);
    border-color: var(--primary-hover-color);
    color: white;
}

.folder-note-item.active .time {
    color: rgba(255, 255, 255, 0.8);
}

/* 美化分割线 */
.divider {
    height: 1px;
    background-color: var(--border-color);
    margin: 12px 12px; /* 增加上下边距 */
}

/* 美化工具栏按钮 */
.toolbar-btn {
    margin: 0 4px;
    padding: 6px 12px;
    border-radius: var(--border-radius);
    border: 1px solid var(--border-color);
    background-color: var(--surface-color);
    color: var(--text-primary);
    cursor: pointer;
    transition: var(--transition);
}

.toolbar-btn:hover {
    background-color: var(--primary-extra-light-color);
    border-color: var(--primary-color);
    color: var(--primary-hover-color);
}

/* 美化输入框 */
.note-title-input {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 6px 8px;
    border-radius: var(--border-radius);
    border: 1px solid var(--border-color);
    background-color: var(--surface-color);
    color: var(--text-primary);
    font-size: 14px;
    transition: var(--transition);
    margin: 0 8px;
}

.note-title-input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 2px rgba(135, 206, 235, 0.2);
}

.note-title-input .ant-input {
    padding: 4px 0;
    font-size: 14px;
    line-height: 1.5;
}

.note-title-input .ant-input:focus {
    box-shadow: none;
}

/* 美化文件夹名称 */
.folder-name {
    padding: 6px 12px;
    border-radius: var(--border-radius);
    transition: var(--transition);
    cursor: pointer;
}

.folder-name:hover {
    background-color: var(--primary-extra-light-color);
}

/* 美化右侧操作按钮 */
.right-actions {
    display: flex;
    align-items: center;
    margin-left: auto;
}

.right-actions .action-btn {
    margin: 0 2px;
    padding: 4px;
    border: none;
    background: transparent;
    cursor: pointer;
    border-radius: 4px;
    color: var(--text-secondary);
    transition: var(--transition);
}

.right-actions .action-btn:hover {
    background-color: var(--border-color);
    color: var(--primary-color);
}

/* 美化调整条 */
.resize-bar {
    flex: 0 0 4px;
    position: relative;
    color: var(--border-color);
    border-left: 1px solid var(--border-color);
    background-color: var(--surface-color);
    transition: var(--transition);
}

.resize-bar:hover,
.entry-resizing {
    cursor: col-resize;
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

.resize-bar::before {
    content: "";
    position: absolute;
    top: calc(50% - 21px);
    left: 50%;
    transform: translateX(-50%);
    width: 2px;
    height: 2px;
    border-radius: 50%;
    user-select: none;
    display: flex;
    flex-direction: column;
    background-color: currentColor;
    box-shadow: 0 8px 0 currentColor, 0 16px 0 currentColor, 0 24px 0 currentColor,
        0 32px 0 currentColor, 0 40px 0 currentColor;
    transition: var(--transition);
}

.resize-bar:hover::before {
    background-color: white;
    box-shadow: 0 8px 0 white, 0 16px 0 white, 0 24px 0 white,
        0 32px 0 white, 0 40px 0 white;
}

.resize-bar::after {
    content: "";
    position: absolute;
    width: 2px;
    height: 100%;
    border-radius: 10px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: transparent;
    transition: background-color 0.3s ease;
}

.resize-bar:hover::after,
.entry-resizing::after {
    background-color: var(--primary-color);
}
</style>